package com.le.tester.imooc.ccmouse.loop;


import com.le.tester.imooc.ccmouse.common.Node;
import com.le.tester.imooc.ccmouse.recursion.LinkedListCreator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * 描述：链表的反转(循环)
 */
public class LinkedListReverser {

    public Node reverseLinkedList(Node head) {
        //从中间的思想进行循环使用，一部分任务已经完成，另一部分还没有完成
        //需要考虑到新链表头和旧链表头
        Node newHead = null;
        Node curHead = head;

        while (curHead != null) {
            Node next = curHead.getNext();
            curHead.setNext(newHead);
            //现在当前的节点变成了newHead
            newHead = curHead;
            //注意curHead.getNext();
            //所以curHead是需要有值去更新的，那么值是什么呢？就是next
            curHead = next;

        }
        return newHead;

    }

    public static void main(String[] args) {
        LinkedListCreator linkedListCreator = new LinkedListCreator();
        LinkedListReverser linkedListReverser = new LinkedListReverser();

        Node.printLinkedList(linkedListReverser.reverseLinkedList(
                linkedListCreator.createLinkedList(new ArrayList<>())));

        Node.printLinkedList(linkedListReverser.reverseLinkedList(
                linkedListCreator.createLinkedList(Collections.singletonList(1))));

        Node.printLinkedList(linkedListReverser.reverseLinkedList(
                linkedListCreator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5))));

        linkedListReverser.reverseLinkedList(
                linkedListCreator.createLargeLinkedList(1000000));
        System.out.println("done");

    }
}
